package org.geotools.tutorial.quickstart.Utilities;


import org.geotools.data.*;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.util.SimpleInternationalString;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.Name;
import org.opengis.util.InternationalString;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * @author
 * @DesktopJavaDocable disable
 */
public class DataStoreUtilities {

	private DataStoreUtilities() {

	}

	public static DataStore getDataStore(Map params) {
		DataStore dataStore = null;
		try {
			dataStore = DataStoreFinder.getDataStore(params);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return dataStore;
	}

	public static List<Name> getDataStoreNames(DataStore dataStore) {
		List<Name> names = null;
		try {
			if (dataStore != null) {
				names = dataStore.getNames();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return names;
	}

	public static SimpleFeatureSource getFeatureSource(DataStore dataStore, Name name) {
		SimpleFeatureSource featureSource = null;
		try {
			if (dataStore != null) {
				featureSource = dataStore.getFeatureSource(name);
				Iterator<DataStoreFactorySpi> allDataStores = DataStoreFinder.getAllDataStores();
				while (allDataStores.hasNext()) {
					DataStoreFactorySpi next = allDataStores.next();
					DataStore newDataStore = next.createNewDataStore(null);
				}

			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return featureSource;
	}

	public static SimpleFeatureSource getFeatureSource(Map params, Name name) {
		return getFeatureSource(getDataStore(params), name);
	}

	public static boolean ImportShp(SimpleFeatureSource simpleFeatureSource, DataStore targetDataStore) {
		boolean result = false;
		try {
			if (simpleFeatureSource == null || targetDataStore == null) {
				return false;
			}
			Name name = simpleFeatureSource.getName();
			SimpleFeatureType simpleFeatureType = simpleFeatureSource.getSchema();
			SimpleFeatureTypeBuilder typerBuilder = new SimpleFeatureTypeBuilder();
			typerBuilder.init(simpleFeatureType);
			typerBuilder.setName(name.toString());
			typerBuilder.setCRS(simpleFeatureType.getCoordinateReferenceSystem());
			typerBuilder.userData("Name", "王建君");
			SimpleFeatureType newType = typerBuilder.buildFeatureType();
			Map<Object, Object> userData = newType.getUserData();
			userData.put("override.reserved.words", Boolean.TRUE);
			targetDataStore.removeSchema(newType.getTypeName());
			targetDataStore.createSchema(newType);
			SimpleFeatureType schema = targetDataStore.getSchema(newType.getTypeName());
			Map<Object, Object> schemaUserData = schema.getUserData();
			Map<Object, Object> objectMap = schema.getGeometryDescriptor().getUserData();
			Map<Object, Object> objectObjectMap = schema.getAttributeDescriptors().get(0).getUserData();


			//导入并保存要素
			FeatureWriter<SimpleFeatureType, SimpleFeature> featureWriter = targetDataStore.getFeatureWriterAppend(name.toString(), Transaction.AUTO_COMMIT);

			FeatureCollection featureCollection = simpleFeatureSource.getFeatures();
			FeatureIterator iterator = featureCollection.features();
			int totalCount = featureCollection.size();
			int counter = 0;
			while (iterator.hasNext()) {
				SimpleFeature sourceFeature = (SimpleFeature) iterator.next();
				SimpleFeature targetFeature = featureWriter.next();
				targetFeature.setAttributes(sourceFeature.getAttributes());
				//Collection<Property> properties = feature.getProperties();
				//Iterator<Property> propertyIterator = properties.iterator();
				//while (propertyIterator.hasNext()) {
				//	Property property = propertyIterator.next();
				//	simpleFeature.setAttribute(property.getName(), property.getValue());
				//}
				featureWriter.write();
				counter++;
				System.out.println(MessageFormat.format("已导入{0}/{1}", counter, totalCount));
			}
			iterator.close();
			featureWriter.close();
			result = true;
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("导入失败！请检查相关参数");
		}
		System.out.println("导入完成!");
		return result;
	}

	//public static ShapefileDataStore createSimpleFeatureSource(File file) {
	//	ShapefileDataStore result = null;
	//	try {
	//		ShapefileDataStoreFactory shapefileDataStoreFactory = new ShapefileDataStoreFactory();
	//		Map<String, Serializable> params = new HashMap<>();
	//		params.put("url", file.toURI().toURL());
	//		params.put("create spatial index", Boolean.TRUE);
	//		try {
	//			result = (ShapefileDataStore) shapefileDataStoreFactory.createDataStore(params);
	//		} catch (IOException e) {
	//			e.printStackTrace();
	//		}
	//	} catch (MalformedURLException e) {
	//		e.printStackTrace();
	//	}
	//	return result;
	//}

	public static Object[] GetavailableDataStoreNodes() {
		ArrayList<Object> objects = new ArrayList<>();

		return objects.toArray(new Object[objects.size()]);

	}

	public static SimpleFeatureCollection subFeatureCollection(SimpleFeatureSource simpleFeatureSource, int start, int offset) {
		SimpleFeatureCollection simpleFeatureCollection = null;
		try {
			Query query = new Query(simpleFeatureSource.getSchema().getTypeName());
			query.setStartIndex(start);
			query.setMaxFeatures(offset);
			simpleFeatureCollection = simpleFeatureSource.getFeatures(query);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return simpleFeatureCollection;
	}

	public static boolean updateSchema(DataStore dataStore, SimpleFeatureType simpleFeatureType) {
		boolean result = false;
		try {
			String typeName = simpleFeatureType.getTypeName();
			SimpleFeatureTypeBuilder simpleFeatureTypeBuilder = new SimpleFeatureTypeBuilder();
			simpleFeatureTypeBuilder.init(simpleFeatureType);
			InternationalString internationalString = new SimpleInternationalString("I am a Description!");
			simpleFeatureTypeBuilder.setDescription(internationalString);
			//FeatureTypeFactory featureTypeFactory = simpleFeatureTypeBuilder.getFeatureTypeFactory();
			//
			//AttributeTypeBuilder attributeTypeBuilder = new AttributeTypeBuilder(featureTypeFactory);
			//attributeTypeBuilder.binding(Integer.class);
			//AttributeType attributeType = attributeTypeBuilder.buildType();
			//Name name = new NameImpl("NewField");
			//
			//AttributeDescriptor attributeDescriptor = featureTypeFactory.createAttributeDescriptor(attributeType, name, 0, 0, false, null);
			//simpleFeatureTypeBuilder.add(simpleFeatureType.getAttributeCount(), attributeDescriptor);
			SimpleFeatureType newFeatureType = simpleFeatureTypeBuilder.buildFeatureType();
			//JDBCDataStore jdbcDataStore=(JDBCDataStore)dataStore;
			//jdbcDataStore.updateSchema(typeName,newFeatureType);
			dataStore.updateSchema(typeName, newFeatureType);
		} catch (Exception ex) {
			System.out.println(ex);
		}
		return result;
	}
}
